package com.edu.juc.introduction.communication.custom;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintString {
    private int flag = 1;
    ReentrantLock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    void print1() {
        lock.lock();
        try {
            while (flag != 1) {
                try {
                    c1.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName());
            flag = 2;
            c2.signal();
        } finally {
            lock.unlock();
        }
    }

    void print2() {
        lock.lock();
        try {
            while (flag != 2) {
                try {
                    c2.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName());
            flag = 3;
            c3.signal();
        } finally {
            lock.unlock();
        }
    }

    void print3() {
        lock.lock();
        try {
            while (flag != 3) {
                try {
                    c3.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName());
            System.out.println(Thread.currentThread().getName());
            flag = 1;
            c1.signal();
        } finally {
            lock.unlock();
        }
    }
}
